@echo off
chcp 65001 >nul
echo ==========================================
echo 启动仓库3D系统服务（后台模式）
echo ==========================================

REM 设置工作目录
set WORKSPACE=%~dp0
cd /d "%WORKSPACE%"

REM 日志轮转函数
:rotate_log
if exist "%~1" (
    for %%F in ("%~1") do (
        if %%~zF GTR 10485760 (
            echo. > "%~1"
            echo 已清空过大的日志文件: %~1
        )
    )
)
exit /b

REM 检查并轮转日志文件
call :rotate_log "%WORKSPACE%server\server.log"
call :rotate_log "%WORKSPACE%plc-service\plc-service.log"
call :rotate_log "%WORKSPACE%queue-service\queue-service.log"
call :rotate_log "%WORKSPACE%rules-engine\rules-engine.log"
call :rotate_log "%WORKSPACE%node-red-integration\node-red.log"
call :rotate_log "%WORKSPACE%client\client.log"

echo 正在后台启动数据库后端服务器...
start "sqlite Server" /min cmd /c "cd /d %~dp0server && npm start > server.log 2>&1"

REM 等待主服务启动
timeout /t 3 /nobreak >nul

REM 启动PLC服务
echo 正在后台启动PLC服务...
start "PLC Service" /min cmd /c "cd /d %~dp0plc-service && npm start > plc-service.log 2>&1"

REM 等待PLC服务启动
timeout /t 3 /nobreak >nul

REM 启动队列服务
echo 正在后台启动队列服务...
start "Queue Service" /min cmd /c "cd /d %~dp0queue-service && npm start > queue-service.log 2>&1"

REM 启动规则引擎服务
echo 正在后台启动规则引擎服务...
start "Rules Engine" /min cmd /c "cd /d %~dp0rules-engine && npm start > rules-engine.log 2>&1"

REM 启动Node-RED集成服务
echo 正在后台启动Node-RED服务...
start "Node-RED" /min cmd /c "cd /d %~dp0node-red-integration && npm start > node-red.log 2>&1"

echo.
echo 正在后台启动前端服务器...
start "Frontend" /min cmd /c "cd /d %~dp0client && npm run dev > client.log 2>&1"

echo.

echo 所有服务已在后台启动
chcp 65001 >nul
echo 数据库服务: http://localhost:3001
echo PLC服务: http://localhost:3002
echo 队列服务: http://localhost:3003
echo 规则引擎: http://localhost:3004
echo Node-RED: http://localhost:1880
echo.
echo 主画面: http://localhost:5175
echo.
echo 日志文件已保存到各服务目录中
echo.
echo 按任意键关闭此窗口...
pause >nul